package middleware

import (
	"BlazeRider-backend/app/utils"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

// AuthMiddleware 验证登录态的 Token 中间件
func LiveRoomAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从请求头中获取 Token
		token := c.GetHeader("Authorization")
		if token == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "missing token"})
			c.Abort()
			return
		}

		// 去掉 "Bearer " 前缀
		token = token[len("Bearer "):]

		// 解析 Token
		claims, err := utils.ParseToken(token)
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
			c.Abort()
			return
		}

		// 检查 Token 是否过期
		if claims.ExpiresAt.Unix() < time.Now().Unix() {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "token expired"})
			c.Abort()
			return
		}

		// 将解析的参数存储在上下文中
		c.Set("room_id", claims.RoomId)
		c.Set("anchor_open_id", claims.AnchorOpenId)
		c.Set("avatar_url", claims.AvatarUrl)
		c.Set("nick_name", claims.LiveNickName)
		c.Next()
	}
}
